package xyz.labmem.lipx.core.handler

import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent
import xyz.labmem.lipx.core.protocol.LabMessage
import xyz.labmem.lipx.core.protocol.LabMessageType
import xyz.labmem.lipx.core.tool.LogInfo
import java.net.InetSocketAddress
import java.net.SocketException

/**
 * @description: do something
 * @author: ltty
 * @date: 2022/5/30 15:21
 */
abstract class LabCommonHandler : ChannelInboundHandlerAdapter() {

    var ctx: ChannelHandlerContext? = null

    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {
        this.ctx = ctx
    }

    @Throws(Exception::class)
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        val ip = (ctx.channel()?.remoteAddress() as InetSocketAddress).address.hostAddress
        when (cause) {
            is SocketException -> LogInfo.appendLogError("[$ip]断开连接![${cause.message}]")
            else -> {
                if (LogInfo.debug) cause.printStackTrace()
                LogInfo.appendLogError("捕捉到异常${cause.message}")
            }
        }
    }

    @Throws(Exception::class)
    override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {
        if (evt is IdleStateEvent) {
            if (evt.state() == IdleState.READER_IDLE) {
//                StaticLog.info("连接丢失,关闭通信.......")
                ctx.close()
            } else if (evt.state() == IdleState.WRITER_IDLE) {
                LabMessage().apply {
                    type = LabMessageType.KEEPALIVE
                    ctx.writeAndFlush(this)
                }
            }
        }
    }

}